<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<html>
<head>
    <title>图书管理</title>
    <meta name="decorator" content="default"/>
    <script>

        function setCookie(c_name, value, expiredays)
        {
            var exdate=new Date();
            exdate.setDate(exdate.getDate() + expiredays);
            document.cookie=c_name+ "=" +escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
        }
        function getCookie(c_name)
        {
            if (document.cookie.length>0)
            {
                c_start=document.cookie.indexOf(c_name + "=");
                if (c_start!=-1)
                {
                    c_start=c_start + c_name.length+1;
                    c_end=document.cookie.indexOf(";",c_start);
                    if (c_end==-1) c_end=document.cookie.length;
                    return unescape(document.cookie.substring(c_start,c_end))
                }
            }
            return ""
        }

        document.onkeydown = function (event) {
            var e = event || window.event || arguments.callee.caller.arguments[0];
            if (e.altKey && e.keyCode == 83) {
                $("#purchaseDetailsForm").submit();
            }else if(e.altKey && e.keyCode == 66){
                window.parent.refresh = true;
                parent.$.jBox.close(true);
            }
        };
        $(document).ready(function() {
            $("#amount").focus();

            defaultAmount();

            $("#purchaseDetailsForm").validate({
                submitHandler: function(form){
                    var banIds = $("#banids").val();
                    if (banIds != "") {
                        $.post("${ctx}/book/store/checkRepeatBanId", {banIds: banIds}, function (result) {
                            if (result.code == '0001') {
                                window.parent.refresh = true;
                                form.submit();
                            } else {
                                var dataStr = "书库中已经存在重复的索书号：<br/>";
                                var data = result.data;
                                for (var i = 0; i < data.length; i++) {
                                    dataStr += data[i] + "<br/>";
                                }
                                alertx(dataStr);
                            }
                        });
                    } else {
                        var isAutoCreate = $("input[name='autoCreateBanId']").is(':checked');
                        if (!isAutoCreate) {
                            alertx("请先分配索书号");
                        }
                        else{
                            // 查看数据库中是否设置好了初始的条码号
                            $.post("${ctx}/book/purchase/isSetUpStartBanId", {banIds: banIds}, function (result) {
                                if (result.code == '0001') {
                                    window.parent.refresh = true;

                                    if (isDefaultAmount()) {
                                        setCookie("default_amount", $("#amount").val(), 99999);
                                    }

                                    form.submit();
                                } else {
                                    confirmx("还没有设置初始条码号，请前去设置", "${ctx}/book/purchase/gotoSetUpStartBanId");
                                }
                            });
                        }
                    }
                },
                rules: {
                    booksAmount: {required:true,digits:true,min:1},
                    amount: {required:true,digits:true,min:1},
                    realPrice:{required:true,number:true,min:0.01},
                    store:{required:true}
                },
                messages: {
                    booksAmount: {required: "必填",digits:"填写数字",min:"大于1"},
                    amount: {required: "必填",digits:"填写数字",min:"大于1"},
                    realPrice:{required:"必填",number:"填写正确数字",min:"大于0"},
                    store:{required:"必填"}
                },
                errorContainer: "#messageBox",
                errorPlacement: function(error, element) {
                    $("#messageBox").text("输入有误，请先更正。");
                    if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
                        error.appendTo(element.parent().parent());
                    } else {
                        error.insertAfter(element);
                    }
                }
            });

            var booksAmount = $("input[name='booksAmount']").val();
            setPerPrice(booksAmount);

            // 默认选中自动生成条形码
            isAutoCreateBanId();
        });

        function isDefaultAmount(){
            return $("#default_amount").is(":checked");
        }

        function defaultAmount(){
            var default_amount =1;
            if (isDefaultAmount()) {
                default_amount = getCookie("default_amount");
                if (!default_amount) {
                    default_amount = 1;
                }
            } else {
                default_amount = 1;
            }
            $("#amount").val(default_amount);
        }

        function leftBooks(){
            var classcode= "${bookinfo.classcode}";
            var bkId = "${bookinfo.id}";
            var isBooks = false;
            var booksNum = $("#booksNum").val();
            var left_books = $("#left_books").is(":checked");

            if (left_books) {
                isBooks = false;
                classcode = "${bookinfo.className}";
            }else{
                isBooks = ${not empty bookinfo.books};
            }
            $.post("${ctx}/book/purchase/createPlace",
                    {bkId:bkId, classcode:classcode, isBooks:isBooks, booksNum:booksNum},
                    function (result) {
                        $("#place").val(result);
                    });
        }

        function checkPlace() {
            var place = $("#place").val();
            top.$.jBox.open("iframe:${ctx}/book/purchase/checkPlace?classcode=" + place, "索书号检查", 800, 600,
                {
                    buttons: {}, closed: function () {
                    var newPlace = window.parent.place;
                    if(newPlace && newPlace != ''){
                        $("#place").val(newPlace);
                    }
                }
            });
        }
        function distributBanId() {
            var isAutoCreate = $("input[name='autoCreateBanId']").is(':checked');
            if (!isAutoCreate) {
                var amount = $("input[name='amount']").val();
                var booksAmount = $("input[name='booksAmount']").val();
                var banids = $("#banids").val();
                parent.$.jBox.open("iframe:${ctx}/book/store/distributBanId?amount=" + amount + "&booksAmount=" + booksAmount + "&banids=" + banids,"分配条形码",
                        300,400,{
                            buttons: {}, closed: function () {
                                $("#banids").val(window.parent.banIds);
                                window.parent.banIds = "";
                        }
                        });
            }
        }
        function isAutoCreateBanId(){
            var isAutoCreate = $("input[name='autoCreateBanId']").is(':checked');
            if(isAutoCreate){
                $("#distributBanId_btn").attr("disabled","true");
                $("#distributBanId_div").hide();
                $("#autoCreateBanId_div").show();
            }
            else{
                $("#distributBanId_btn").removeAttr("disabled");
                $("#distributBanId_div").show();
                $("#autoCreateBanId_div").hide();
            }
        }
        function keyUp(obj) {
            var booksAmount = $(obj).val();
            setPerPrice(booksAmount);
        }
        function setPerPrice(booksAmount) {
            if (booksAmount.trim() != '') {
                var priceStr = '${bookinfo.price}';
                var price = parseFloat(priceStr.split('(')[0]);
                var pPrice = (price / booksAmount).toFixed(2);
                $("input[name='pPrice']").val(pPrice);
            }
        }

        function changeStartBanId(){
            $("#change_btn").hide();
            $("#setup_btn").show();

            $("#maxBarCode").removeAttr("disabled");
        }

        function setupStartBanId(){
            var maxBarCode = $("#maxBarCode").val();
            $.ajax({
                type: "POST",
                url: "${ctx}/book/purchase/setUpStartBanId",
                data: {startsn: maxBarCode},
                dataType: "json",
                success: function (data) {
                    parent.$.jBox.info(data.msg, '提示', {
                        closed: function () {
                            $("#change_btn").show();
                            $("#setup_btn").hide();
                            $("#maxBarCode").attr("disabled","true");
                        }
                    });
                }
            });
        }
    </script>
    <style>
        .field {
            width: 80px;
            text-align: right;
        }

        .inp_ln {
            width: 130px!important;
            height: 15px!important;
            font-size: 12px!important;
        }
        .inp_mi{
            width: 40px!important;
            height: 15px!important;
            font-size: 12px!important;
        }
        .inp_mini{
            width: 100px!important;
            height: 15px!important;
            font-size: 12px!important;
        }
        .inp_long{
            width: 450px!important;
            height: 15px!important;
            font-size: 12px!important;
        }
        td {
            height: 30px;
        }
        .input-medium{
            width: 130px;
        }
        .select2-container .select2-choice{
            height: 22px;
        }
    </style>
</head>
<body>
<form:form id="purchaseDetailsForm" modelAttribute="store" action="${ctx}/book/purchase/check" method="post"
           cssStyle="margin-top: 10px;" autocomplete="off" class="form-horizontal">
    <form:input path="bkId" cssStyle="display: none;"/>
    <form:input path="bookname" cssStyle="display: none;"/>
    <form:input path="batch" cssStyle="display: none;"/>
    <table border="1" cellpadding="0" cellspacing="0" style="width: 100%;">
        <tr>
            <td colspan="3">当前验收批次号：<label style="color: red;font-weight: bolder;">${batch.batchNumber}</label></td>
        </tr>
        <tr>
            <td>
                <label class="field">币种：</label>
                <form:select path="moneyType" items="${fns:getDictList('money')}" class="input-medium" />
            </td>
            <td>
                <label class="field">复本数：</label>
                <form:input id="amount" cssClass="inp_ln" path="amount"/>
                <input id="default_amount" type="checkbox" onclick="defaultAmount()" checked>默认
            </td>
            <td>
                <label for="left_books">
                    <input id="left_books" type="checkbox" onclick="leftBooks()" ${empty bookinfo.books?'disabled':''}>单独编目
                </label>
            </td>
        </tr>
        <tr>
            <td>
                <label class="field">原价：</label>
                ${bookinfo.price}
            </td>
            <td>
                <label class="field">卷册数量：</label>
                <form:input cssClass="inp_ln" path="booksAmount"  onkeyup='keyUp(this)'/>
            </td>
            <td>
                <label class="field">文献来源：</label>
                <form:select path="source" items="${fns:getDictList('source')}" itemLabel="label" itemValue="value" class="input-medium" />
            </td>
        </tr>
        <tr>
            <td>
                <label class="field">单册价格：</label>
                <form:input cssClass="inp_ln" path="pPrice" value="${bookinfo.price}"/>
            </td>
            <td>
                <label class="field">卷册信息：</label>
                <input id="booksNum" type="text" class="inp_ln" value="${bookinfo.booksNum}"/>
            </td>
            <td>
                <label class="field">装帧形式：</label>
                <form:select path="binding" items="${fns:getDictList('binding')}" itemLabel="label" itemValue="value" class="input-medium" />
            </td>
        </tr>
        <tr>
            <td>
                <label class="field">整套价格：</label>
                <form:input cssClass="inp_ln" path="tPrice"/>
            </td>
            <td>
                <label class="field">索书号：</label>
                <form:input id="place" path="place" cssClass="inp_mini" value="${place}"/>
                <a href="javascript:checkPlace()" class="btn btn-small">索书号检查</a>
            </td>
            <td>
                <label class="field">备注信息：</label>
                <form:input cssClass="inp_ln" path="msg"/>
            </td>
        </tr>
        <tr>
            <td>
                 <label class="field">采访币种：</label>
                 <form:select path="pMoneyType" items="${fns:getDictList('money')}" itemLabel="label" itemValue="value" class="input-mini" />
                <label>折扣率：</label>
                <input class="inp_mi" type="text" name="discount"/>
            </td>
            <td>
                <label class="field">采访价格：</label>
                <form:input cssClass="inp_ln" path="realPrice"/>
            </td>
            <td>
                <label class="field">分配书库：</label>
                <form:select id="store" path="store" items="${fns:getAllStoreList(false)}"
                             itemLabel="gcdName"
                             itemValue="placeid" class="input-medium" />
            </td>
        </tr>
        <tr>
            <td colspan="3">
                <label for="autoCreateBanId">
                    <input id="autoCreateBanId" name="autoCreateBanId" type="checkbox"
                           value="1" checked onclick="isAutoCreateBanId()">自动生成
                </label>
                <label id="distributBanId_div">
                    <label class="field">条形码：</label>
                    <form:input id="banids" path="banid" readonly="true" cssClass="inp_long"/>
                    <a id="distributBanId_btn" href="javascript:distributBanId()" onclick="" class="btn btn-small">分配条形码</a>
                </label>
                <label id="autoCreateBanId_div" style="margin-left: 10px;">
                    起始条码号：<input id="maxBarCode" name="maxBarCode" value="${maxBarCode}" disabled type="text" class="inp_mini"/>
                    <a id="change_btn" href="javascript:void(0);" onclick="changeStartBanId()">修改</a>
                    <a id="setup_btn" href="javascript:void(0);" onclick="setupStartBanId()" style="display: none;">提交</a>
                </label>
            </td>
        </tr>
    </table>
    <div class="form-actions" style="padding-left: 350px;">
        <input id="btnSubmit" type="submit" class="btn btn-primary submit" value="保存 Alt+S" />
        <input type="button" class="btn btn-primary" onclick="parent.$.jBox.close(true);" value="取消 Alt+B" />
    </div>
</form:form>
</body>
</html>